﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Quellenverwaltung.Meta
{
    public class ReadMetaDataFromHtml
    {
        public Dictionary<string, string> ReadMetaData(string url)
        {
            Dictionary<string, string> meta = new Dictionary<string, string>();

            // Download page
            //WebClient client = new WebClient();
            //string html = client.DownloadString(url);

            WebClientEncoding client = new WebClientEncoding();
            string html = client.DownloadPage(url);

            // Scan links on this page
            HtmlTag tag;
            HtmlParser parse = new HtmlParser(html);
            while (parse.ParseNext("meta", out tag))
            {
                // See if this anchor links to us
                string nameValue;
                string contentValue;
                string schemeValue;

                if (tag.Attributes.TryGetValue("name", out nameValue)
                    || tag.Attributes.TryGetValue("property", out nameValue))
                {

                    if (tag.Attributes.TryGetValue("content", out contentValue))
                    {
                        if (tag.Attributes.TryGetValue("scheme", out schemeValue))
                        {
                            if (!meta.ContainsKey(nameValue + "::" + schemeValue))
                            {
                                meta.Add(nameValue + "::" + schemeValue, contentValue);
                            }
                        }
                        else
                        {
                            if (!meta.ContainsKey(nameValue))
                            {
                                meta.Add(nameValue, contentValue);
                            }
                        }
                    }
                }
            }
            if (!meta.ContainsKey("title"))
            {
                string title = Regex.Match(html, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                meta.Add("title", title);
            }

            meta.Add("url", url);

            return meta;
        }

    }
}
